package com.salt.admin.api.kit;

import com.salt.admin.api.model.MultiTenant;
import com.salt.admin.api.model.User;
import com.salt.admin.api.utils.TenantClientUtils;
import com.salt.admin.api.utils.UserClientUtils;
import com.salt.common.utils.StringUtils;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @Description 数据权限
 * @Author salt
 * @Date 2022/1/22
 * @Version 1.0.1
 */
@Component
public class DataAuth {

    public void verifyAddAuth(Object o) {
        User user = UserClientUtils.getUser();
        if (!user.isAdmin()) { // 是不是超级管理员
            MultiTenant multiTenant = TenantClientUtils.find();
            if (multiTenant != null) {  // 是不是具有多租户权限
                addDataAuth(o, null, multiTenant.getTenantIds());
            } else {  // 不是超级管理员也不具有租户权限
                if (user.getCompany() != null && StringUtils.isNotBlank(user.getCompany().getId()))
                    addDataAuth(o, user.getCompany().getId(), null);
            }
        }
    }

    @SneakyThrows
    public void addDataAuth(Object o, String tenant, List<String> tenantIds) {
        Class<? extends Object> aClazz = o.getClass();
        //Field[] declaredFields = aClazz.getDeclaredFields(); // 获取当前类
        Class<?> superclass = aClazz.getSuperclass(); // 获取父类
        Field[] declaredFields = superclass.getDeclaredFields();
        if (StringUtils.isNotBlank(tenant)) {
            for (int i = declaredFields.length-1; i >= 0; i --) {
                Field field = declaredFields[i];
                field.setAccessible(true);
                Class<?> fieldType = field.getType();
                String fieldName = field.getName();
                if ("java.lang.String".equals(fieldType.getName())) {
                    Method setValMethod = aClazz.getMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), String.class);
                    if ("tenant".equals(fieldName)) {
                        setValMethod.invoke(o, tenant);
                        return;
                    }
                }
            }
        } else if (tenantIds != null && !tenantIds.isEmpty()) {
            for (int i = declaredFields.length-1; i >= 0; i --) {
                Field field = declaredFields[i];
                field.setAccessible(true);
                Class<?> fieldType = field.getType();
                String fieldName = field.getName();
                if ("java.util.List".equals(fieldType.getName())) {
                    Method setValMethod = aClazz.getMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), List.class);
                    if ("tenantIds".equals(fieldName)) {
                        setValMethod.invoke(o, tenantIds);
                        return;
                    }
                }
            }
        }
    }
}
